<template>
  <div class="mats-pane">
    <el-container>
      <el-header class="title-bar" height="auto">
        <el-row>
          <el-col :span="10">
          <!--
          <span class="title">{{ modeTitle }}</span>
          <span class="count">（{{ num }}/{{ totalCount }}）</span>
          -->
          <el-menu class="mode-menu" mode="horizontal" :default-active="modePath(mode)" @select="menuChanged">
            <el-menu-item index="fav">我的收藏<sub>（{{stats.fav}}）</sub></el-menu-item>
            <el-menu-item index="discover">衍星收录<sub>（{{stats.discover}}）</sub></el-menu-item>
            <el-menu-item v-if="hasResource" index="resources">资源仓库<sub>（{{stats.resources}}）</sub></el-menu-item>
          </el-menu>
          </el-col>
          <el-col :span="14">
            <span class="right-bar">
              <el-radio-group v-model="viewMode" size="mini">
                <el-radio-button label="grid"><ri i="grid"></ri></el-radio-button>
                <el-radio-button label="list"><ri i="list"></ri></el-radio-button>
              </el-radio-group>
            </span>


            <span class="right-bar">
              <el-divider direction="vertical"></el-divider>
              <sorter class="sorter" :options="sortOptions" v-model="orderby" @change="orderChanged()"></sorter>
            </span>
            <span class="right-bar">
              <el-input v-model="keyword" size="mini" class="search-input" placeholder="搜索" @change="searchMats">
                <el-button slot="prepend" icon="el-icon-search" @click="searchMats"></el-button>
                <el-select slot="append" v-model="searchType" @change="changeSearchType">
                  <el-option label="标题" value="t"></el-option>
                  <el-option label="内容" value="c"></el-option>
                  <el-option label="作者" value="a"></el-option>
                </el-select>
              </el-input>
              <el-button type="warning" size="mini" icon="el-icon-refresh" @click="randomMats" >{{fav ? '随机' : '推荐'}}</el-button>
              <el-button v-if="isCoding" type="success" size="mini" icon="el-icon-aim" @click="importProject">导入</el-button>
              <el-button v-else-if="isPins" class="right" type="primary" size="mini" icon="el-icon-edit" @click="addPin">创建记事</el-button>
              <el-button v-else type="primary" size="mini" icon="el-icon-circle-plus" @click="addMat" >添加</el-button>
            </span>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <scroller height="84vh">
        <ul class="mat-list" :class="viewMode">
          <li class="mat-item"  v-for="(p, i) in mats" :key="i">
            <mat-card v-if="viewMode == 'list'" :mat="p" @edit-tags="editTags"></mat-card>
            <mat-grid-card v-if="viewMode == 'grid'" :mat="p" @edit-tags="editTags"></mat-grid-card>
          </li>
          <div id="pageLoader" class="mat-list-pager">
            <el-button v-if="showHasMore" @click="loadMore()">加载更多...</el-button>
          </div>
        </ul>
        </scroller>
      </el-main>
      <edit-tags :tags="tags" :cats="cats" :kind="kind" :mat="mat" :visible.sync="tagsDialogVisible"></edit-tags>
    </el-container>

    <div>
      <el-dialog title="编辑素材" :visible.sync="editDialogVisible">
        <edit-mat :kind="kind" @cancel="editDialogVisible=false"></edit-mat>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import MatCard from "./MatCard.vue";
import MatGridCard from "./MatGridCard.vue";
import EditTags from "./EditTags.vue";
import EditMat from "@comps/mats/EditMat.vue";
import Scroller from "../tools/Scroller.vue";
import Sorter from "../tools/Sorter.vue";
import { EVENTS, EVENT_BUS } from "src/eventbus.js";
import { MatKind, MatMode, NoteScope, NoteKind } from '../../js/constants';
import paths from '@/js/utils/paths';

const DEFAULT_LIMIT = 9;
export default {
  props: ["mode", "kind", "cats"],
  components: {
    MatCard,
    MatGridCard,
    EditTags,
    EditMat,
    Scroller,
    Sorter,
  },
  watch: {
    mode() {
      this.clear();
      this.fetchMats();
    }
  },
  data() {
    return {
      MatKind: MatKind,
      MatMode: MatMode,
      showResources: false,
      stats: {
        fav: 0,
        discover: 0,
        resources: 0
      },
      resourceSearch: "",
      filter: null,
      mats: [],
      totalCount: 0,
      limit: DEFAULT_LIMIT,
      offset: 0,
      orderby: this.fav ? 'f' : 't',
      keyword: '',
      searchType: 't',
      random: false,
      sortOptions: [{
        value: 'f',
        label: '按收藏时间'
      }, {
        value: 't',
        label: '按时间'
      }, {
        value: 'n',
        label: '按名称'
      }, {
        value: 'h',
        label: '按热度'
      }, {
        value: 's',
        label: '按星量'
      }],
      mat: {},
      tags: [],
      tagsDialogVisible: false,
      editDialogVisible: false,
      viewMode: this.getViewMode()
    };
  },
  computed: {
    num() {
      return this.mats.length;
    },
    showHasMore() {
      if (this.random) return false;
      return this.totalCount > this.mats.length;
    },
    fav() {
      return this.mode == MatMode.Fav;
    },
    isResource() {
      return this.mode == MatMode.Resources;
    },
    isCoding() {
      return this.kind == MatKind.Project;
    },
    isPins() {
      return this.kind == MatKind.Pin;
    },
    modeTitle() {
      switch(this.mode) {
        case MatMode.Fav:
          return "我的收藏";
        case MatMode.Discover:
          return "衍星收录";
        case MatMode.Resources:
          return "资源仓库";
        default:
          return "我的收藏";
      }
    },
    hasResource() {
      return [MatKind.Book, MatKind.Poem].includes(this.kind);
    },
  },
  created() {
    this.fetchStats();
    // 初始化诗歌列表
    this.fetchMats();
    // TODO: 添加默认搜索条件
    EVENT_BUS.$on(EVENTS.MATS_FILTER, (f) => {
      this.clear()
      this.filter = f;
      this.fetchMats();
    });
  },
  methods: {
    getViewMode() {
      let kinds = [MatKind.Book, MatKind.Poem, MatKind.ArticleSet, MatKind.Pin];
      return kinds.includes(this.kind) ? 'grid' : 'list';
    },
    modePath(index) {
      switch(index) {
        case MatMode.Fav:
          return "fav";
        case MatMode.Discover:
          return "discover";
        case MatMode.Resources:
          return "resources";
        default:
          return "fav";
      }
    },
    changeSearchType() {
      if (this.keyword != "") {
        this.searchMats();
      }
    },
    menuChanged(index) {
      let path = this.$route.path;
      let root = paths.getRoot(path);
      let p = paths.join(root, index);
      console.log("path to go:", p);
      if (p != path) {
        this.$router.push(p);
      } else {
        this.clear();
        this.searchMats();
      }
    },
    fetchStats() {
      this.authGet("/api/v1/mats/stats?k="+this.kind).then(res => {
        this.stats = res.data;
      })
    },
    clear() {
      this.totalCount = 0;
      this.limit = DEFAULT_LIMIT;
      this.offset = 0;
      this.orderby = this.fav ? 'f': 't';
      this.random = false;
      this.filter = null;
      this.keyword = "";
      //this.mats = [];
    },
    editTags(mat) {
      this.tags = mat.tags || [];
      this.mat = mat;
      this.tagsDialogVisible = true;
    },
    randomMats() {
      //this.clear();
      this.random = true;
      this.fetchMats();
    },
    searchMats() {
      let keyword = this.keyword;
      this.clear();
      this.keyword = keyword;
      this.fetchMats();
    },
    orderChanged() {
      this.mats = [];
      this.fetchMats();
    },
    loadMore() {
      let loader = document.getElementById("pageLoader");
      loader.style = "display: none;";
      this.offset += this.limit;
      this.fetchMats(true);
    },
    // 向后台请求素材列表
    fetchMats(isAppend) {
      let s = "?";
      s += "limit="+this.limit + "&offset=" + this.offset;
      if (this.filter) {
        if (this.filter.kind == "author") {
          s = s + "&author=" + this.filter.value.id;
        } else if (this.filter.kind == "tag") {
          s = s + "&tag=" + this.filter.value.id;
        }
      }
      s += "&o=" + this.orderby;
      if (this.random) {
        s += "&r=1"
      }
      if (s == "?") s = "";
      
      if (this.keyword) {
        s += "&sk=" + this.keyword;
        s += "&st=" + this.searchType;
      }

      if (this.kind) {
        s += "&k=" + this.kind;
      }

      if (this.mode == MatMode.Fav) {
        this.authGet("/api/v1/mats/fav" + s)
          .then((res) => {
            if (isAppend) {
              this.appendMats(res.data);
            } else {
              this.resetMats(res.data);
            }
          }).catch((err) => { console.log("error getting poems: " + err); });
      } else {
        let url = "";
        if (this.mode == MatMode.Discover) {
          url = "/api/v1/mats/search"; 
        } else {
          url = "/api/v1/mats/resources"; 
        }
        this.$axios
          .get(url + s)
          .then((res) => {
            if (isAppend) {
              this.appendMats(res.data);
            } else {
              this.resetMats(res.data);
            }
          }).catch((err) => { console.log("error getting mat: " + err); });
      }
    },
    processMats(mats) {
      let ms = mats;
      ms.forEach((m) => {
        if (m.star === undefined) {
          m.star = {
            mid: m.id,
            kind: NoteKind.Star,
            scope: NoteScope.Article,
            value: 0,
          };
        }
        // 将标签按照类别和名称排序
        if (m.tags) {
          m.tags.sort((x, y) => x.cat - y.cat != 0 ? x.cat - y.cat : x.val - y.val);
        } else {
          m.tags = [];
        }
      });
      return ms;
    },
    resetMats(data) {
      console.log("resetting mats");
      this.totalCount = data.total;
      this.mats = this.processMats(data.mats);
      this.loadStars();
    },
    appendMats(data) {
      console.log("appending mats");
      this.totalCount = data.total;
      let ms = this.processMats(data.mats);
      this.mats = this.mats.concat(ms);
      this.loadStars();
      // 再次显示”加载更多“按钮。这么做是为了不让滚动条直接跳到新加载的末尾
      let loader = document.getElementById("pageLoader");
      loader.style = "display: block;"; 
    },
    loadStars() {
      if (this.mats.length == 0) return;
      let ids = this.mats.map((p) => p.id);
      this.authPost("/api/v1/stats/mats", ids).then((res) => {
        let statsList = res.data;
        let smap = {};
        for (let stats of statsList) {
          let mid = stats.mid;
          smap[mid] = stats;
        }
        for (let i = 0; i < this.mats.length; ++i) {
          let m = this.mats[i];
          if (m.id in smap) {
            let stats = smap[m.id];
            let c = {};
            Object.assign(c, m);
            c.stats = stats;
            this.$set(this.mats, i, c);
          }
        }
      });
    },
    addMat() {
      //this.$router.push("/mats/edit?kind=" + this.kind);
      this.editDialogVisible = true;
    },
    importProject() {
      this.$router.push("/coding/import");
    },
    addPin() {
      this.$router.push("/pins/edit");
    }
  },
};
</script>

<style lang="stylus">
.mats-pane
  text-align left
  padding 0

  .title-bar
    line-height 4.5vh
    .mode-menu
      width 25vw
      .el-menu-item
        height auto
        min-height 4.5vh
        line-height 4.5vh
        font-size 1em
        font-weight bold
        padding 0 0.4vw

        sub
          font-weight normal

    .search-input
      width 15vw
      .el-input-group__prepend
        padding 0 0.6vw
      .el-input-group__append
        width 2vw
        padding 0 0.9vw

  >.el-container>.el-main
    padding 1vh 1vw 0 1vw

  .mat-list-pager
    text-align center

  .mat-list.grid
    display flex
    flex-wrap wrap

    .mat-item
      list-style none

  .mat-list>.notice
    margin-top 50px
    text-align center

  .title-bar
    .count
      color #999

    .el-input
      margin-right 10px

</style>